package com.laogu1.handler;

import com.alibaba.fastjson.JSONObject;
import com.lagou.pojo.Request;
import com.lagou.util.ZkUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.BeansException;
import org.springframework.cglib.reflect.FastClass;
import org.springframework.cglib.reflect.FastMethod;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 自定义业务处理器
 */
@Component
public class UserServiceHandler extends ChannelInboundHandlerAdapter implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    private static ZkClient zkClient = new ZkClient(ZkUtil.ZK_ADDRESS);

    /**
     * 当客户端读取数据时，该方法会被调用
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        long startTime = System.currentTimeMillis();
        System.out.println(JSONObject.toJSONString(msg));
        Request request = (Request) msg;

        Class<?> clazz = Class.forName(request.getClassName());
        Object serviceBean = applicationContext.getBean(clazz);

        Class<?> serviceClass = serviceBean.getClass();

        FastClass fastClass = FastClass.create(serviceClass);
        FastMethod fastMethod = fastClass.getMethod(request.getMethodName(), request.getParameterType());
        fastMethod.invoke(serviceBean, request.getParameters());

        ctx.writeAndFlush("success!");
        long costTime = System.currentTimeMillis() - startTime;
        if (zkClient.exists(ZkUtil.PATH + "/127.0.0.1_7999")) {
            String str = startTime + "_" + costTime;
            System.out.println(str);
            zkClient.writeData(ZkUtil.PATH + "/127.0.0.1_7999", str);
        }
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        UserServiceHandler.applicationContext = applicationContext;
    }
}
